const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const jwt = require('koa-jwt');
const favicon = require('koa-favicon');
const path = require('path');

const routers = require('./routes/index');
const config = require('./config/config.json');
const middlewaresList = require('./middlewares/index');
const log4js = require('./lib/log');
const errLogger = log4js.getLogger('error');

// 上下文配置日志方法
app.context.log = log4js.getLogger();

// 格式化异常情况的页面输出
onerror(app);

// 中间件
app.use(middlewaresList.crossDomain);
app.use(bodyparser({ enableTypes: ['json', 'form', 'text'] }));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));
app.use(views(__dirname + '/public', { map: { html: 'ejs' } }));
app.use(favicon(path.join(__dirname, '/public/favicon.ico')));
app.use(jwt({ secret: config.sign }).unless({
  path: [/^\/api\/v1\/public/]
}))
// 动态加载中间件
for (let key in middlewaresList) {
  if (!middlewaresList.hasOwnProperty(key)) continue;
  app.use(middlewaresList[key]);
}

// 路由
app.use(routers.routes())
  .use(routers.allowedMethods());

// 异常处理
app.on('error', (err, ctx) => {
  errLogger.error(err.message);
  ctx.body = {
    status: false,
    message: err.message
  }
});

module.exports = app;
